import React from 'react';
import { Table, type TabsProps, Tabs, Breadcrumb, Row, Col, Space, message, Modal } from 'antd';
import { PlusCircleFilled, EditOutlined, DeleteFilled } from '@ant-design/icons';
import _ from 'lodash';
import { FormPanel, InputType, type FormPanelObject, FormPanelStatus, Utils } from 'lfun-bg-comp';
import { useParams } from 'react-router-dom';
import dayjs from 'dayjs';
import { PageContainer } from '@/component/page-container';
import style from './index.less';
import ToolMenu from './toolMenu';
import { Org, SearchMembersParams, searchMembers, searchOrg } from '@/service/unit/org';
import { PageParams, PageResult, Result } from '@/service';
import Create from './create';
import Delete from './delete';
import Update from './update';
import { PAGINATIONCONFIG } from '@/constant/page';
import { GENDER } from '@/constant/basicOptions';
import { ID_TYPE } from '@/constant/studentOptions';
import { get_stoge_pz, set_stoge_pz } from '@/utils';
import PermissionButton, { isPermission, isPermissionOperate } from '@/component/permission-button';

const Groups: React.FC = () => {
  const { id } = useParams();
  const defCurrentData: Org = {
    id: 0,
    org_name: '',
    parent_id: 0,
    school_id: 0,
  };
  const [orgs, setOrgs] = React.useState<any>([]);
  const [currentData, setCurrentData] = React.useState<Org>(defCurrentData);
  const [isAddModal, setIsAddModal] = React.useState<boolean>(false);
  const [isDelModal, setIsDelModal] = React.useState<boolean>(false);
  const [isEditModal, setIsEditModal] = React.useState<boolean>(false);
  const [value, setValue] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  const [curFormPanelObject, setCurFormPanelObject] = React.useState<FormPanelObject>();
  const [member, setMember] = React.useState<any>([]);
  const [tabs, setTabs] = React.useState<TabsProps['items']>([]);
  const [activeKey, setActiveKey] = React.useState<string>('0');
  const [activeKeys, setActiveKeys] = React.useState<React.Key[]>([]);
  const [showDetail, setShowDetail] = React.useState<boolean>(false);
  const handleDelete = () => {
    setIsDelModal(true);
  };
  const defaultTabs = [
    {
      key: '0',
      label: (
        <Space>
          <PermissionButton permission="add">
            <PlusCircleFilled
              onClick={() => {
                setCurrentData(defCurrentData);
                setIsAddModal(true);
              }}
            />
          </PermissionButton>
          <PermissionButton permission="edit">
            <EditOutlined onClick={() => setIsEditModal(true)} />
          </PermissionButton>
          <PermissionButton permission="delete">
            <DeleteFilled onClick={handleDelete} />
          </PermissionButton>
        </Space>
      ),
    },
  ];
  const onChange = (key: string) => {
    if (key !== '0') {
      setActiveKey(key);
    }
  };
  const search = async (param, pageIndex, pageSize) => {
    if (orgs.length === 0) return;
    setLoading(true);
    const params: SearchMembersParams & PageParams = {
      page: pageIndex,
      per_page: pageSize,
      org_ids: activeKeys.join(','),
      ...param,
    };
    const res = await searchMembers(params);
    if (res.success) {
      setTotal(res.data.total);
      setValue(res.data.items);
    } else {
      message.error(res.message || res.details);
    }
    setPageIndex(pageIndex);
    setPageSize(pageSize);
    setLoading(false);
  };
  const isShowTool = id => {
    return activeKey === String(id);
  };
  const init = async (hassetActiveKey = true) => {
    const result: Result<PageResult<Org>> = await searchOrg({ parent_id: 0, school_id: id });

    if (result.success && result?.data?.items && result?.data?.items.length > 0) {
      const curIts: Org[] = result?.data?.items?.filter(it => Number(it.parent_id) === 0);
      if (curIts && curIts.length > 0) {
        if (hassetActiveKey) setActiveKey(String(curIts[0].id));
        const curChildren: any = curIts.map(it => {
          return {
            key: String(it.id),
            label: it.org_name,
          };
        });
        if (curChildren && curChildren.length > 0) setTabs(curChildren.concat(defaultTabs));
        setOrgs([...curIts]);
      }
    }
    search(curFormPanelObject?.getFieldsValue(), pageIndex, pageSize);
  };
  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize);
    search(curFormPanelObject?.getFieldsValue(), pageIndex, pageSize);
  };
  React.useEffect(() => {
    init();
    setTabs(defaultTabs);
  }, []);
  return (
    <PageContainer header={<Breadcrumb items={[{ title: '组织架构管理' }]} />}>
      <Row className={style.bg}>
        <Col span={6} className={style.tool}>
          <Tabs activeKey={activeKey} items={tabs} onChange={onChange} />
          <ToolMenu
            parentId={activeKey}
            onSelect={(selectedKeys: React.Key[]) => {
              if (selectedKeys.length > 0) {
                search({ org_ids: selectedKeys.join(',') }, 1, pageSize);
                setActiveKeys(selectedKeys);
              } else {
                setValue([]);
                setPageIndex(1);
                setPageSize(pageSize);
              }
            }}
          />
        </Col>
        <Col span={18}>
          <FormPanel
            onLoad={(formpanel: FormPanelObject) => setCurFormPanelObject(formpanel)}
            onFinish={(formpanel: FormPanelObject) => {
              search(formpanel.getFieldsValue(), 1, pageSize);
            }}
            template={[
              {
                title: '',
                labelCol: { span: 8 },
                wrapperCol: { span: 14 },
                inputs: [
                  {
                    label: '姓名',
                    name: 'teacher_name',
                    key: 'teacher_name',
                  },
                  {
                    label: '工号',
                    name: 'teacher_number',
                    key: 'teacher_number',
                  },
                  {
                    label: '联系电话',
                    name: 'teacher_mobile',
                    key: 'teacher_mobile',
                  },
                  {
                    label: '出生日期',
                    name: 'teacher_date_of_birth',
                    key: 'teacher_date_of_birth',
                    inputType: InputType.date,
                    formatSubmitValue: value => {
                      if (value && value.isVail && value.isVail()) return dayjs(value).format('YYYY-MM-DD');
                      return value;
                    },
                  },
                ],
              },
            ]}
          />
          <Table
            dataSource={value}
            columns={[
              {
                title: '序号',
                dataIndex: 'idx',
                key: 'idx',
                width: '100',
                render: (text, record, index) => {
                  return index + 1;
                },
              },
              {
                title: '姓名',
                dataIndex: 'member_name',
                key: 'member_name',
                width: '150',
              },
              {
                title: '出生日期',
                dataIndex: 'birthday',
                key: 'birthday',
                width: '150',
                render: (text, record) => {
                  return dayjs(text).format('YYYY-MM-DD');
                },
              },
              {
                title: '性别',
                dataIndex: 'gender',
                key: 'gender',
                width: '100',
                render: (text, record) => {
                  return _.find(GENDER, { value: text })?.label;
                },
              },
              {
                title: '手机号码',
                dataIndex: 'mobile',
                key: 'mobile',
                width: '200',
              },
              {
                title: '证件类型',
                dataIndex: 'card_type',
                key: 'card_type',
                width: '200',
                render: (text, record) => {
                  return _.find(ID_TYPE, { value: text })?.label;
                },
              },
              {
                title: '证件号码',
                dataIndex: 'card_number',
                key: 'card_number',
                width: '200',
              },
              {
                title: '操作',
                key: '操作',
                fixed: 'right',
                //width: '100',
                align: 'center',
                hidden: !isPermissionOperate(),
                render: (text, record) => (
                  <PermissionButton permission="view">
                    <a
                      onClick={() => {
                        setShowDetail(true);
                        setMember(record);
                      }}
                    >
                      查看
                    </a>
                  </PermissionButton>
                ),
              },
            ]}
            loading={loading}
            scroll={{ x: 'max-content' }}
            pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
          />
        </Col>
      </Row>
      <Create
        show={isAddModal}
        onCancel={() => setIsAddModal(false)}
        onOk={(org: Org) => {
          init(false);
          setIsAddModal(false);
          setActiveKey(String(org.id));
        }}
        currentData={currentData}
      />
      <Delete
        show={isDelModal}
        onCancel={() => setIsDelModal(false)}
        onOk={() => {
          init();
          setIsDelModal(false);
        }}
        currentData={(() => {
          if (!currentData.id && orgs.length) return orgs.find(it => String(it.id) === activeKey);
          return currentData;
        })()}
      />
      <Update
        show={isEditModal}
        onCancel={() => setIsEditModal(false)}
        onOk={(org: Org) => {
          init(false);
          setIsEditModal(false);
        }}
        currentData={(() => {
          if (!currentData.id && orgs.length) return orgs.find(it => String(it.id) === activeKey);
          return currentData;
        })()}
      />
      <Modal open={showDetail} footer={null} onCancel={() => setShowDetail(false)}>
        <FormPanel
          formStatus={FormPanelStatus.nonEdit}
          buttonsDisplay="none"
          values={member}
          template={[
            {
              title: '',
              span: 24,
              labelCol: { span: 8 },
              wrapperCol: { span: 14 },
              inputs: [
                {
                  label: '姓名',
                  name: 'member_name',
                  key: 'member_name',
                },
                {
                  label: '出生日期',
                  name: 'birthday',
                  key: 'birthday',
                  formatValue: value => {
                    return dayjs(value).format('YYYY-MM-DD');
                  },
                },
                {
                  label: '性别',
                  name: 'gender',
                  key: 'gender',
                  formatValue: value => {
                    return _.find(GENDER, { value })?.label;
                  },
                },
                {
                  label: '手机号码',
                  name: 'mobile',
                  key: 'mobile',
                },
                {
                  label: '证件类型',
                  name: 'card_type',
                  key: 'card_type',
                  formatValue: value => {
                    return _.find(ID_TYPE, { value })?.label;
                  },
                },
                {
                  label: '证件号码',
                  name: 'card_number',
                  key: 'card_number',
                },
              ],
            },
          ]}
        />
      </Modal>
    </PageContainer>
  );
};

export default Groups;
